package com.toocms.jinjuhang.ui.commodity.detils

import android.app.Application
import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.ImageData
import com.toocms.jinjuhang.data.flow.ConfirmOrderData
import com.toocms.jinjuhang.data.goods.DetailDescData
import com.toocms.jinjuhang.data.goods.GetSpecGoodsAttrData
import com.toocms.jinjuhang.data.goods.GoodsCommentsData
import com.toocms.jinjuhang.data.goods.GoodsDetailData
import com.toocms.jinjuhang.dialog.specification.SpecificationDialog
import com.toocms.jinjuhang.ui.commodity.evaluate.CommodityEvaluateFgt
import com.toocms.jinjuhang.ui.main.MainFgt
import com.toocms.jinjuhang.ui.main.MainFilter
import com.toocms.jinjuhang.ui.mine.order.confirm.ConfirmOrderFgt
import com.toocms.jinjuhang.ui.system.EvaluateItemModel
import com.toocms.jinjuhang.utils.FragmentUtils
import com.toocms.jinjuhang.utils.HtmlUtil
import com.toocms.jinjuhang.widget.view_model.checkLoginStatus
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseActivity
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger
import com.toocms.tab.bus.event.SingleLiveEvent
import com.toocms.tab.share.TabShare
import com.toocms.tab.widget.banner.BannerItem
import com.umeng.socialize.bean.SHARE_MEDIA

class CommodityDetailsModel(application: Application, val bundle: Bundle) :
    BaseViewModel<BaseModel>(application) {

    val goodsId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_GOODS_ID)
    }
    var quantity: String? = null
    var selectedAttrIds: String? = null
    val selectedAttrNamesObservableField = ObservableField<String>()
    val isHaveAttrsObservableBoolean = ObservableBoolean()
    val dataObservableField = ObservableField<GoodsDetailData>()
    val isVisibleServiceAndCartObservableBoolean = ObservableBoolean(false)
    val isVisibleFunctionOne = ObservableBoolean(false)
    val isVisibleFunctionTwo = ObservableBoolean(false)
    val functionOneHint = ObservableField<String>()
    val functionTwoHint = ObservableField<String>()
    val goodsDescObservableField = ObservableField<String>()
    val licenseObservableField = ObservableField<String>()
    val bannerItems = ObservableArrayList<BannerItem>()
    val evaluateItems = ObservableArrayList<EvaluateItemModel>()
    val evaluateItemBinding =
        ItemBinding.of<EvaluateItemModel>(BR.evaluateItemModel, R.layout.item_evaluate)
    val extraFilterObservableField = ObservableField(ExtraFilter.PRODUCT_DETAILS)
    val extraFilterSingleLiveEvent = SingleLiveEvent<ExtraFilter>()
    val productDetailsClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        extraFilterSingleLiveEvent.value = ExtraFilter.PRODUCT_DETAILS
        extraFilterObservableField.set(extraFilterSingleLiveEvent.value)
    })
    val displayQualificationClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        extraFilterSingleLiveEvent.value = ExtraFilter.DISPLAY_QUALIFICATION
        extraFilterObservableField.set(extraFilterSingleLiveEvent.value)
    })

    val backClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        finishFragment()
    })

    val shareClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
//        CommodityShareDialog().show(
//            (ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager, null
//        )
        if (!checkLoginStatus()) return@BindingAction
        dataObservableField.get()?.share?.apply {
            when (UserRepository.user.level) {
                "1" ->
                    TabShare.getOneKeyShare()
                        .setPlatform(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setMin(
                            "https://www.baidu.com/",
                            share_title,
                            share_content,
                            "pages/lanhu_111shouye/index?goods_id=${goodsId}&member_sn=${UserRepository.user.member_sn}",
                            Constants.ThirdPartyInfo.WECHAT_ORIGINAL_ID,
                            share_cover
                        )
                        .share()
                else ->
                    TabShare.getOneKeyShare()
                        .setPlatform(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setLayout(R.id.share)
                        .share()
            }
        }
    })

    val collectBindingCommand = BindingCommand<BindingAction>(BindingAction {
        if (!checkLoginStatus()) return@BindingAction
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["goods_id"] = goodsId
        requestData(Urls.Goods.DO_COLLECT, params, resultClass = String::class.java, result = {
            showToast(it)
            requestData()
        })
    })

    val specificationClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        showSpecificationDialog(OpenSpecificationAction.SELECTED)
    })

    val evaluateMoreClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragment(CommodityEvaluateFgt::class.java, bundle)
    })

    val cartClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        if (!checkLoginStatus()) return@BindingAction
        Messenger.getDefault().send(MainFilter.CART, Constants.MessengerToken.TOKEN_MAIN_FILTER)
        FragmentUtils.popTo(MainFgt::class.java, false)
    })

    val functionOneBindingCommand = BindingCommand<BindingAction>(BindingAction {
        dataObservableField.get()?.apply {
            if (!checkLoginStatus()) return@BindingAction
            when (goods_type) {
                Constants.Extra.COMMODITY_TYPE_GENERAL -> {
                    //TODO 立即领取
                    if (isHaveAttrsObservableBoolean.get() && selectedAttrIds.isNullOrEmpty()) {
                        showSpecificationDialog(OpenSpecificationAction.RECEIVE)
                    } else {
                        action(OpenSpecificationAction.RECEIVE)
                    }
                }
                Constants.Extra.COMMODITY_TYPE_GET -> {

                }
                Constants.Extra.COMMODITY_TYPE_INTEGRAL -> {
                }
            }
        }
    })
    val functionTwoBindingCommand = BindingCommand<BindingAction>(BindingAction {
        dataObservableField.get()?.apply {
            if (!checkLoginStatus()) return@BindingAction
            when (goods_type) {
                Constants.Extra.COMMODITY_TYPE_GENERAL -> {
                    //TODO 加入购物车
                    if (isHaveAttrsObservableBoolean.get() && selectedAttrIds.isNullOrEmpty()) {
                        showSpecificationDialog(OpenSpecificationAction.ADD_CART)
                    } else {
                        action(OpenSpecificationAction.ADD_CART)
                    }
                }
                Constants.Extra.COMMODITY_TYPE_GET -> {
                    //TODO 立即领取
                    if (isHaveAttrsObservableBoolean.get() && selectedAttrIds.isNullOrEmpty()) {
                        showSpecificationDialog(OpenSpecificationAction.RECEIVE)
                    } else {
                        action(OpenSpecificationAction.RECEIVE)
                    }
                }
                Constants.Extra.COMMODITY_TYPE_INTEGRAL -> {
                    //TODO 立即兑换
                    if (isHaveAttrsObservableBoolean.get() && selectedAttrIds.isNullOrEmpty()) {
                        showSpecificationDialog(OpenSpecificationAction.CHANGE)
                    } else {
                        action(OpenSpecificationAction.CHANGE)
                    }
                }
            }
        }
    })


    init {
        extraFilterSingleLiveEvent.value = ExtraFilter.PRODUCT_DETAILS
        requestData(true)
    }

    override fun onStop() {
        super.onStop()
        TabShare.release()
    }

    private fun requestData(isShowLoading: Boolean = false) {
        //商品详情
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["goods_id"] = goodsId
        requestData(Urls.Goods.GOODS_DETAIL,
            params,
            resultClass = GoodsDetailData::class.java,
            isShowLoading = isShowLoading,
            result = {
                quantity = if (quantity?.toInt() ?: 0 > it.stock?.toInt() ?: 0) {
                    it.stock ?: "0"
                } else {
                    "1"
                }
                dataObservableField.set(it)
                licenseObservableField.set(license(it.license))
                bannerItems.clear()
                it.pictures?.forEach {
                    bannerItems += BannerItem().apply {
                        imgUrl = it.abs_url
                    }
                }
                isVisibleServiceAndCartObservableBoolean.set(false)
                isVisibleFunctionOne.set(false)
                isVisibleFunctionTwo.set(false)
                functionOneHint.set("")
                functionTwoHint.set("")
                when (it.goods_type) {
                    Constants.Extra.COMMODITY_TYPE_GENERAL -> {
                        isVisibleServiceAndCartObservableBoolean.set(true)
                        isVisibleFunctionOne.set(true)
                        functionOneHint.set(StringUtils.getString(R.string.str_immediately_receive))
                        isVisibleFunctionTwo.set(true)
                        functionTwoHint.set(StringUtils.getString(R.string.str_add_cart))
                    }
                    Constants.Extra.COMMODITY_TYPE_GET -> {
                        isVisibleFunctionTwo.set(true)
                        functionTwoHint.set(StringUtils.getString(R.string.str_immediately_receive))
                    }
                    Constants.Extra.COMMODITY_TYPE_INTEGRAL -> {
                        isVisibleServiceAndCartObservableBoolean.set(true)
                        isVisibleFunctionTwo.set(true)
                        functionTwoHint.set(StringUtils.getString(R.string.str_immediately_change))
                    }
                }
            })
        //获取规格
        requestData(Urls.Goods.GET_SPEC_GOODS_ATTR,
            params,
            resultClass = GetSpecGoodsAttrData::class.java,
            result = {
                isHaveAttrsObservableBoolean.set(!it.list.isNullOrEmpty())
                selectedAttrNamesObservableField.set(it.list?.get(0)?.attr_values?.get(0)?.attr_value)
            })
        //商品图文详情
        requestData(Urls.Goods.DETAIL_DESC,
            params,
            resultClass = DetailDescData::class.java,
            result = {
                goodsDescObservableField.set(it.goods_desc)
            })
        //商品评价
        params["page_size"] = "3"
        params["p"] = "1"
        requestData(Urls.Goods.GOODS_COMMENTS,
            params,
            resultClass = GoodsCommentsData::class.java,
            result = {
                evaluateItems.clear()
                it.list?.forEach {
                    evaluateItems += EvaluateItemModel(this, ObservableField(it))
                }
            },
            error = {
                evaluateItems.clear()
            })
    }

    private fun showSpecificationDialog(action: OpenSpecificationAction) {
        if (!checkLoginStatus()) return
        SpecificationDialog().apply {
            goodsId = this@CommodityDetailsModel.goodsId
            selectedAttrIds = this@CommodityDetailsModel.selectedAttrIds
            selectedAttrNames = this@CommodityDetailsModel.selectedAttrNamesObservableField.get()
            goodsName = this@CommodityDetailsModel.dataObservableField.get()?.goods_name
            goodsType = this@CommodityDetailsModel.dataObservableField.get()?.goods_type
            quantity = this@CommodityDetailsModel.quantity?.toInt() ?: 0
            onConfirmClickListener = { tag, attrIds, attrNames, quantity ->
                this@CommodityDetailsModel.selectedAttrIds = attrIds
                this@CommodityDetailsModel.quantity = quantity
                this@CommodityDetailsModel.selectedAttrNamesObservableField.set(attrNames)
                action(OpenSpecificationAction.code2action(tag))
            }
        }.show((ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager, action.code)
    }


    private fun action(action: OpenSpecificationAction) {
        when (action) {
            OpenSpecificationAction.SELECTED -> {

            }
            OpenSpecificationAction.ADD_CART -> {
                addToCart()
            }
            OpenSpecificationAction.RECEIVE -> {
                if (!checkLoginStatus()) return
                if (0 < quantity?.toInt() ?: 0) {
                    var url = ""
                    val params = mutableMapOf<String, String?>()
                    params["member_id"] = UserRepository.user.member_id
                    url = Urls.Flow.FAST_CONFIRM_ORDER
                    params["goods_id"] = goodsId
                    params["quantity"] = quantity
                    params["goods_attr_ids"] = selectedAttrIds
                    params["goods_attr_desc"] = selectedAttrNamesObservableField.get()
                    requestData(url, params, resultClass = ConfirmOrderData::class.java, result = {
                        startConfirmOrderFgt()
                    })
                } else {
                    showToast(R.string.str_understock_hint)
                }
            }
            OpenSpecificationAction.CHANGE -> {
                if (!checkLoginStatus()) return
                if (0 < quantity?.toInt() ?: 0) {
                    //检测积分是否足够
                    val params = mutableMapOf<String, String?>()
                    params["member_id"] = UserRepository.user.member_id
                    params["goods_id"] = goodsId
                    params["goods_attr_ids"] = selectedAttrIds
                    params["quantity"] = quantity
                    requestData(
                        Urls.Goods.CHECK_POINTS,
                        params,
                        resultClass = String::class.java,
                        result = {
                            startConfirmOrderFgt()
                        })
                } else {
                    showToast(R.string.str_understock_hint)
                }
            }
        }
    }

    private fun startConfirmOrderFgt() {
        val bundle = Bundle()
        bundle.putString(Constants.BundleKey.KEY_GOODS_ID, goodsId)
        bundle.putString(
            Constants.BundleKey.KEY_GOODS_ATTR_IDS, selectedAttrIds
        )
        bundle.putString(Constants.BundleKey.KEY_QUANTITY, quantity)
        startFragment(ConfirmOrderFgt::class.java, bundle)
    }

    private fun addToCart() {
        if (!checkLoginStatus()) return
        if (0 == quantity?.toInt() ?: 0) {
            showToast(R.string.str_understock_hint)
            return
        }
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["goods_id"] = goodsId
        params["goods_attr_ids"] = selectedAttrIds
        params["quantity"] = quantity
        requestData(Urls.Cart.ADD_TO_CART,
            params,
            resultClass = String::class.java,
            isShowLoading = true,
            result = {
                showToast(it)
                Messenger.getDefault().sendNoMsg(Constants.MessengerToken.TOKEN_REFRESH_CART)
            })
    }

    fun showPrice(sum: String?): CharSequence = when (dataObservableField.get()?.goods_type) {
        Constants.Extra.COMMODITY_TYPE_INTEGRAL -> {
            val sum = if (sum.isNullOrEmpty()) "00" else sum
            SpannableStringBuilder("$sum${StringUtils.getString(R.string.str_integral)}").apply {
                setSpan(
                    RelativeSizeSpan(1.5f), 0, sum.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                setSpan(
                    StyleSpan(Typeface.BOLD), 0, sum.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
        else -> {
            val sum = if (sum.isNullOrEmpty()) "0.00" else sum
            val symbol = StringUtils.getString(R.string.str_money_symbol)
            val unit = StringUtils.getString(R.string.str_money_unit)
            SpannableStringBuilder("$symbol$sum$unit").apply {
                setSpan(
                    RelativeSizeSpan(1.5f),
                    symbol.length,
                    sum.length + 1,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                setSpan(
                    StyleSpan(Typeface.BOLD),
                    symbol.length,
                    sum.length + 1,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
    }

    private fun license(license: List<ImageData>?): String {
        if (license.isNullOrEmpty()) return ""
        val content = StringBuilder()
        license.forEach {
            content.append("""<img src="${it.abs_url}" width=100%/>""")
        }
        return HtmlUtil.optimizeContent("""<div style="font-size:0;">${content.toString()}</div>""")
    }
}